package cn.util;

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import cn.bean.Image;
import cn.log.Log;
import dao.PictureDao;
import dao.PictureGroupDao;

public class HttpUtil {
	private static int connectTimes = 5;
	private static int PICTRUE_GROUPSEQ = PictureGroupDao.getMaxId().intValue();

	//获取网页格式的内容为字符串
	public static String getHtmlContent(String url){
		StringBuffer content= new StringBuffer();
		try {
			URL u = new URL(url);
			BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream()));
			String input;
			while((input = br.readLine()) != null){
				content.append(input);
			}
			br.close();
			Log.info("content-->"+content);
		} catch (Exception e) {
			e.printStackTrace();
			if(connectTimes > 0){
				getHtmlContent(url);
				--connectTimes;
				Log.info("连接-》"+connectTimes);
			}else{
				Log.error("获取内容失败");
				return null;
			}
		}
		return content.toString();
	}
	
	/*//分析网页代码，找到匹配的图片地址
	public static Map getImgUrl(String content){
		Map m = new HashMap();
		String imgReg = "(<a\\s([\\w]+=\"\\S*\"\\s)+(title=\"点击图片查看下一张\"){1}\\s>)(<img src=\"http://[^s]*((.jpg)|(.png))\")";
//		String imgUrlReg = "http:\"?(.*?)(\"|>|\\s+^\\')";
//		String imgUrlReg ="/((http://)+(.*)((.gif)|(.jpg)|(.bmp)|(.png)|(.GIF)|(.JPG)|(.PNG)|(.BMP)))/";
		String imgUrlReg = "http://[^s]*((.jpg)|(.png))";
		String imgNextUrlReg = "http://[\\S]+";
		List imgUrlArray = new ArrayList();
		List imgSrcs = new ArrayList();
		//String searchImgReg = "(?x)(src|SRC|background|BACKGROUND)=('|\")/?(([\\w-]+/)*([\\w-]+\\.(jpg|JPG|png|PNG|gif|GIF)))('|\")";
		Matcher matcher =Pattern.compile(imgReg).matcher(content);
		while(matcher.find()){
			Log.info(matcher.group());
			imgUrlArray.add(matcher.group());
			
		}
		Log.info("imgUrls-->"+imgUrlArray.toString());
		String nextUrl=null;
		for(int i=0;i<imgUrlArray.size();i++){
			Matcher m2 = Pattern.compile(imgUrlReg).matcher((String)imgUrlArray.get(i));
			Matcher m3 = Pattern.compile(imgNextUrlReg).matcher(((String)imgUrlArray.get(i)));
			Log.info("if matches to imgUrls-->"+m2.matches());
			while(m2.find()){
				Log.info(m2.group());
				imgSrcs.add(m2.group());
			}
			while(m3.find()){
				Log.info("nextUrl-->"+m3.group());
				if(!m3.group().contains(".jpg"))
				nextUrl = m3.group().replace("\"", "");
			}
		}
		m.put("ImgSrcs", imgSrcs);
		m.put("nextImgUrl", nextUrl);
		return m;
	}*/
	

	
	public static Image getImageInfoByUrl(String url){
		Image img = new Image();
		Document doc = null;
		try {
			doc = Jsoup.connect(url).timeout(60000).get();
			String name = doc.title().split(" ")[0];
			img.setName(new String(name.getBytes("UTF-8")));
			for(Element link : doc.getElementsByAttributeValue("title", "点击图片查看下一张")){
				img.setNextUrl(link.attr("href"));
				Document e = Jsoup.parse(link.html());
				for(Element l : e.getElementsByTag("img")){
					img.setSrc(l.attr("src"));
				}
			}
			String imgUrl = img.getSrc();
			URL src = new URL(imgUrl);
			BufferedImage bi = ImageIO.read(src);
			int width = bi.getWidth();;
			int height = bi.getHeight();
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			ImageIO.write(bi, "jpg", os);
			byte[] data = os.toByteArray();
			int size = data.length/1024;//kb
			img.setSize(size);
			img.setHeight(height);
			img.setWidth(width);
			img.setImgData(data);
			
		} catch (IOException e) {
			if(connectTimes > 0){
				getImageInfoByUrl(url);
				--connectTimes;
			}else{
				Log.info("获取图片信息失败，无法连接");
				return null;
			}
			
		}
		Log.info("获取图片信息成功-->"+img.toString());
		if(isEmpty(img.getNextUrl())){
			img.setNextUrl(getNextUrl(doc));
		}
		return img;
	}
	
	public static boolean saveHtmlImage2DB(Image img,String filePath){
		boolean success = true;
		Map saveData = new HashMap();
		Map imgMap = ObjUtil.obj2Map(img);
		String imgUrl = img.getSrc();
		try{
			Log.info("获取网络图片-->"+imgUrl);
			if(imgUrl == null){
				Log.error("获取图片地址为空，无法保存图片");
				return false;
			}
			String fileName = (imgUrl.substring(imgUrl.lastIndexOf("/")));
			
			Log.info(imgMap);
			if(img.getNextUrl().endsWith("/2")){
				Log.info("新的图片组");
				++PICTRUE_GROUPSEQ;
				HashMap m = new HashMap();
				m.put("Name", img.getName());
				//m.put("Pid", );
				PictureGroupDao.addPictureGroup(m);
				Log.info("插入新的图片组成功");
			}
			img.setGroupId(PICTRUE_GROUPSEQ);
			imgMap = ObjUtil.obj2Map(img);
			if(!PictureDao.isExistSrc(imgMap)){
				PictureDao.addPicture(imgMap);
				Log.info("图片信息保存数据库成功-->"+img.toString());
			}else{
				Log.info("图片路径以存在");
			}
			
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return success;
	}
	
	private static void addPicture(Map imgMap) {
		// TODO Auto-generated method stub
		
	}

	public static String getNextUrl(Document doc){
		String nextUrl = null;
		for(Element e : doc.select("div a span")){
			if(e.html().length() > 3 && "下一组»".equals(e.html().trim())){
				nextUrl = e.parent().attr("href");
				Log.info("下一组-->" + nextUrl);
			}
		}
		
		return nextUrl;
		
	}
	
	public static void saveHtml2File(String urlStr , String filePath){
		try {
			URL url = new URL(urlStr);
			File file = new File(filePath);
			if(!file.exists()){
				file.createNewFile();
			}
			InputStream in = url.openStream();
			int t = 0;
			FileOutputStream fout = new FileOutputStream(filePath);
			while((t=in.read()) != -1){
				fout.write(t);
			}
			fout.flush();
			fout.close();
			in.close();
			
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static boolean isEmpty(String str){
		if(str != null && str.length() > 0){
			return false;
		}else{
			return true;
		}
	}
}
